# -*- coding: utf8 -*-
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import login_required
from yamw.models import *
from yamw.utils import render_to_response, not_login
import sys

class TaskHomePage(webapp.RequestHandler):
    """ 任务管理主页 """
    
    @login_required
    def get(self):
        """ 
            进入Task列表画面, 显示最新的任务列表
            任务和任务组混合按照时间排序, 时间较近的在前,
            同一个任务组中priority高的在前较近的在前, 完成的在后
            今天
              task
              task
              taskgroup
                task
                task
            昨天
              task
              taskgroup
           2008/07/02
            ...
            ...
        """
        
        # 当前用户
        user = users.get_current_user()
        
        # 取得所有未分组的任务
        nogroup_tasks = Task.all().filter('user =', user).filter('group =', None).fetch(200, 0)
        
        # 取得所有的任务组
        groups = TaskGroup.all().filter('user =', user).order('create_date').fetch(200)
        
        # 把任务和任务组合并
        items = nogroup_tasks + groups
        
        # 按照创建时间排序
        items = sorted(items, cmp=lambda x,y: -cmp(x.create_date, y.create_date))

        context = {
            'tasks' : items,
            'taskgroups' : groups,
            'request' : self.request
        }
        
        render_to_response(self.response, "task.html", context)
          
    def put(self):
        """ 添加任务 """
        
        user = users.get_current_user()
        if not user:
            not_login(self.response)
            return
        
        print self.request.get('item','')
        print self.request.get('group_id')
        
        context = {
            'task' : Task(),
            'request' : self.request
        }
        
        render_to_response(self.response, "task.xml", context)
    
class TaskGroupPage(webapp.RequestHandler):
    """ 任务组管理 """
    
    @login_required
    def get(self, id=None):
        """ 如果id存在则取得特定任务, 如果id不存在则取得任务组列表 """
        
        context = {
            'request' : self.request
        }
        
        if id:
            tg = TaskGroup.get_by_id(id)
            context['group'] = tg
            render_to_response(self.response, "taskgroup.xml", context)
        else:
            user = users.get_current_user()
            groups = TaskGroup.all().filter('user =', user)
            context['groups'] = groups
            render_to_response(self.response, "taskgrouplist.xml", context)
            
    @login_required        
    def put(self):
        """ 创建新的任务组 """
        
        
        pass


class TaskPage(webapp.RequestHandler):
    """ 任务资源页 """
    
    @login_required
    def get(self, id):
        out = self.response.out
        out.write("<html><body>")
        out.write("<h1>Task Page of %s </h1>" % id)
        out.write("</body></html>")